package node_game

import (
	"fmt"
	"math/rand"
	"sanguo/cluster"
	"sanguo/cs"
	"sanguo/node/common/IDGen"
	"sanguo/node/common/db"
	battlelevelDef "sanguo/node/table/battlelevel"
	excel "sanguo/node/table/excel/table"
	missionDef "sanguo/node/table/mission"
	"strconv"
	"strings"
	"time"
)

var areaID_ uint16
var serverID_ byte
var teamService cluster.Service

func verify() bool {
	str := `
		local r = redis.call('hget',KEYS[1],ARGV[1])
		if not r then
			redis.call('hset',KEYS[1],ARGV[1],ARGV[2])
			return 'ok'
		elseif r == ARGV[2] then
			return 'ok'
		else
			return 'failed'
		end		
	`
	keys := []string{}
	keys = append(keys, "serverID")
	ret, err := db.GetRedisClient("login").Eval(str, keys, fmt.Sprintf("%d", serverID_), GetSelfService().ToPeerID().ToString()).Result()

	if nil != err || ret != "ok" {
		Infoln("Redis Error :", err, ret)
		return false
	} else {
		return true
	}
}

func Start(areaID uint16, serverID byte, externalAddr string) error {
	if areaID > IDGen.AreaIDMax {
		return fmt.Errorf("areaID > AreaIDMax")
	}

	if !missionDef.Load("table/xml/mission") {
		return fmt.Errorf("Load missionDef failed")
	}

	if !battlelevelDef.Load("table/xml/battlelevel") {
		return fmt.Errorf("Load battlelevelDef failed")
	}

	excel.Load("table/excel/table/")

	areaID_ = areaID
	serverID_ = serverID

	if !verify() {
		return fmt.Errorf("verify failed")
	}
	//初始化随机种子
	rand.Seed(time.Now().Unix())

	t := strings.Split(externalAddr, ":")
	port, _ := strconv.Atoi(t[1])
	return cs.StartTcpServer("tcp", fmt.Sprintf("0.0.0.0:%d", port), &gDispatcher)
	//return cs.StartTcpServer("tcp", externalAddr, &gDispatcher)
}

func GetAreaID() uint16 {
	return areaID_
}

func GetServerID() byte {
	return serverID_
}

func SetTeamServer(teamAddr string) {
	t := strings.Split(teamAddr, ":")

	ip := t[0]
	port, _ := strconv.Atoi(t[1])
	teamService = cluster.MakeService("team", ip, int32(port))
}

func GetTeamServer() cluster.Service {
	return teamService
}
